/// <reference path="../base.js" />
/// <reference path="../3rdParty/Mootools-Core.js" />

/* Pardus Sector Tool
 * (C) Yassen 2010
 *
 * config.js
 * Defines functions for interacting with the configuration options.
 *
 * Functions:
 * void    Read()
 * void    Write()
 * String  Get(key)
 * void    Set(key, value)
 *
 */

Utility.Config.Data = { "Version": CookieVersion,
  "Imagepack": "http://static.pardus.at/img/stdhq",
  "DefaultBuildingLevel": 1
};

Utility.Config.Ready = false;
Utility.Config.CookieName = "PardusEconConfig";

Utility.Config.Register = function(key, value)
{
  /// <summary>Registers a config value.</summary>
  /// <param name="key" type="String">Name</param>
  /// <param name="value" type="Mixed">Default Value</param>
  /// <returns value="void"></returns>
  
  Utility.Config.Data[key] = value;
}

Utility.Config.UnRegister = function(key)
{
  /// <summary>Deletes a config value.</summary>
  /// <param name="key" type="String">Name</param>
  /// <returns value="void"></returns>
  
  delete Utility.Config.Data[key];
}

Utility.Config.Read = function()
{
  if (Utility.Config.Ready)
    return;

  // Read Cookie (JSON format)
  var cookie = Cookie.read(Utility.Config.CookieName);

  if (cookie == null || JSON.decode(cookie, true) == null)
  {
    Utility.Config.Write();
    cookie = Cookie.read(Utility.Config.CookieName);
  }

  Utility.Config.Data = JSON.decode(cookie);
  Utility.Config.Ready = true;

  EventSink.fireEvent("ConfigLoaded");
}

Utility.Config.Write = function()
{
  Cookie.write(Utility.Config.CookieName, JSON.encode(Utility.Config.Data), { duration: 356 });
}

Utility.Config.Get = function(key)
{
  /// <summary>Gets the value associated with the key.</summary>
  /// <param name="key" type="String">Key to find value with.</param>
  /// <returns type="String">Value</returns>

  Utility.Config.Read();
  return Utility.Config.Data[key];
}

Utility.Config.Set = function(key, value)
{
  /// <summary>Sets key to value</summary>
  /// <param name="key" type="String">Key to set the value of.</param>
  /// <param name="value" type="Mixed">Value to set key to.</param>
  /// <returns type="void"></returns>

  if (Utility.Config.Data[key] == value) // No change
    return;
    
  Utility.Config.Data[key] = value;
  Utility.Config.Write();
}